<?php

namespace App\Services\MakeCouponsUsePoints;

use App\Models\User;
use App\Models\Order;
use Carbon\Carbon;
use App\Models\Activity;
use App\Models\Coupon;
use App\Models\CouponRecord;
use Illuminate\Support\Facades\Redis;
use App\Http\Controllers\Api\V1\Requests\FormRequest;
use Rainsens\Dinglog\Facades\Dinglog;

class TakeCouponsRequest extends FormRequest
{
	public function rules()
	{

		return [
			'coupon_id' => [
				'required',
				'integer',
				'min:1',
				$this->coupon(),
			],
			'activity_id' =>  [
				'required',
				'integer',
				'min:1',
				 $this->acticity()
			]
			
		];
	}

	public function acticity()
	{
		return function ($key, $value, $fail) {
			$activity = Activity::find($this->activity_id);
			if(!$activity){

				fail("该活动不存在！");
			}


			$count=CouponRecord::query()->where("activity_id",$activity->id)->where("user_id",$this->user()->id)->whereDate("created_at",Carbon::now())->count();
			if(big_decimal($activity->quantity)->isLessThanOrEqualTo($count)){

				fail("用户领取已达上限!");
			}

			return true;

		};	

	}

	public function coupon()
	{
		return function ($key, $value, $fail) {

			$coupon = Coupon::find($this->coupon_id);
			if($coupon->total < 1){

				fail("优惠卷已抢光");
			}
			return true;
		};
	}

	

}
